import React, { Component, Fragment } from 'react';
import { Button, Spin, Form, Input, Upload, Icon, Tooltip, Select, Checkbox } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import router from 'umi/router';
import EditPage from '@/components/EditPage';
import AntdForm from '@/components/AntdForm';
import AntdInput from '@/components/AntdInput';
import AntdDatePicker from '@/components/AntdDatePicker';
import FileReader from '@/components/FileReader';
import AntdFormItem from '@/components/AntdFormItem';
import AdSelect from '@/components/AdSelect';
import AdButton from '@/components/AdButton';
import SearchSelect from '@/components/SearchSelect';
import ExportOSInfo from './ExportOSInfo';
import ExportAddress from './Address/ExportAddress';
import AdModal from '@/components/AdModal';
import ManageList from '@/components/ManageList';
import AntdSelectRegion from '@/components/AntdSelectRegion';
import {
    formItemFragement,
    queryDict,
    filterAddFile,
    filterDeteteFile,
    columnsCustomer,
} from '@/utils/common';
import prompt from '@/components/Prompt';
import { allDictList } from '@/utils/constans';
import {
    formateTime,
    allDispatchType,
    allUrl,
    routeUrl,
    selectExportOSList,
    incotermList,
    containerSizeList,
} from './utils';
import styles from './exportOs.less';

const { TextArea } = Input;
const { Option } = Select;

@ManageList
@connect(({ exportOS, component, loading }) => ({
    exportOSDetail: exportOS.exportOSDetail,
    cargoInfoList: exportOS.cargoInfoList,
    formValues: exportOS.formValues,
    dictObject: component.dictObject,
    customerList: component.customerList,
    loading: loading.effects[allDispatchType.detail],

}))
@Form.create()
export default class ExportOSOperate extends Component {
    constructor(props) {
        super(props)
        this.state = {
            detailId: '',
            selectedRows: [],
            disabled: false,
            showTips: false,
            isCustomDeclaration: false,
            isExportBillsPurchase: false,
            getDataFirst: {
                orderNo: true
            },
            visibleAddress: false, //init false
            addressType: '',
            spickupAddress: {},
            deliveryAddress: {},
            truckTypeList: [],
            consignorCode:""
        };
    }
    fileList = [];
    deleteInfoIds = [];
    userToken = localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')) : {};

    componentWillMount() {
        // const allDict = [allDictList.papersType, allDictList.currencyType];
        // queryDict({ props: this.props, allDict });
    }

    componentDidMount() {
        const {
            match: {
                params: { id },
            },
            exportOSDetail,
        } = this.props;

        this.getTruckTypeList();
        if (!id) {
            this.child.addInfo(1);
            this.setState({
                deliveryAddress: this.userToken && this.userToken.defaultAddres ? this.userToken.defaultAddress : {}
            })
            return;
        }
        this.handleStateChange([{ detailId: id }]);
        this.selectExportOSDetail(id);
    }

    getTruckTypeList = () => {
        const { dispatch, searchValue } = this.props;
        dispatch({
            type: allDispatchType.getTruckTypeList,
            payload: {},
            callback: data => {
                if (!data) return;
                let newArr = [];
                data.map((v) => {
                    newArr.push({ code: v, value: v })
                })

                this.setState({
                    truckTypeList: newArr
                })
            },
        });
    }

    selectExportOSDetail = id => {
        const { dispatch, form } = this.props;
        dispatch({
            type: allDispatchType.detail,
            payload: { id },
            callback: data => {
                const { orderPartList, files, isCustomDeclaration, isExportBillsPurchase, deliveryFullParentIds } = data;
                this.fileList = files || [];
                const dataFields = [{ files: data.files || [] }];
                dataFields.map(v => {
                    form.setFieldsValue(v);
                });
                if (orderPartList && orderPartList.length > 0) {

                } else {
                    this.child.addInfo(1);
                }
                this.formatAddress(data.pickupFullParentIds, 'pickupCity');
                this.formatAddress(data.deliveryFullParentIds, 'deliveryCity');

                // 字段联络人是提货人
                this.setState({
                    isCustomDeclaration,
                    isExportBillsPurchase,
                    spickupAddress: {
                        name: data.contactPerson,
                        phone: data.contactNumber,
                        fullParentIds: data.pickupFullParentIds,
                        fullParentNames: data.pickupCity,
                        address: data.pickupDetailAddress
                    },
                    deliveryAddress: {
                        name: data.deliveryContactPerson,
                        phone: data.deliveryContactNumber,
                        fullParentIds: data.deliveryFullParentIds,
                        fullParentNames: data.deliveryCity,
                        address: data.deliveryDetailAddress
                    }
                });
            },
        });
    };

    headerOperate = () => {
        const { detailId, disabled } = this.state;
        const { exportOSDetail } = this.props;
        const detail = exportOSDetail[detailId] || {};
        return (
            <div>
                {disabled ? (
                    <AdButton
                        type="primary"
                        onClick={() => {
                            this.setState(preState => ({
                                disabled: !preState.disabled,
                            }));
                        }}
                        disabled={detail.status == "1"||detail.status == '4'}
                        text="编辑"
                    />
                ) : (
                        <Button.Group>
                            <AdButton
                                text="保存"
                                disabled={detail.status == "1"||detail.status == '4'}
                                type="primary"
                                onClick={this.saveInfo}
                            />
                            {detailId && (
                                <AdButton
                                    onClick={() => {
                                        this.setState(preState => ({
                                            disabled: !preState.disabled,
                                        }));
                                    }}
                                    text="取消"
                                />
                            )}
                        </Button.Group>
                    )}
            </div>
        );
    };

    /**
     * 获取表单内容
     */
    getCityCode = (val) => {
        if (!val) return '';
        const newVal = val.split(',');
        return newVal.length == 3 ? newVal[newVal.length - 2] : newVal[newVal.length - 1];
    }
    saveInfo = () => {
        const {
            form,
            exportOSDetail,
            cargoInfoList,
            match: {
                params: { id },
            },
        } = this.props;
        const { spickupAddress, deliveryAddress } = this.state;
        form.validateFieldsAndScroll((errors, values) => {
            // if (errors) return;
            const { pickupDateTime, deliveryCity, pickupCity, files, ...params } = values;
            //对应文档--- 发货人就是提货人  送货是收货
            // 1、地址信息
            //1-1 提货信息 （发货）
            // console.log('spickupAddress', spickupAddress, 'deliveryAddress', deliveryAddress)
            const { fullParentIds, address, name, phone } = spickupAddress;
            params.contactPerson = name;
            params.contactNumber = phone;
            params.pickupFullParentIds = fullParentIds;
            params.pickupDetailAddress = spickupAddress.address;
            params.pickupCityCode = this.getCityCode(fullParentIds);

            // 1-2 送货信息  （收货）
            //deliveryContactPerson (string, optional):  送货联络人 , （收货）
            //pickupCityCode (string, optional):  提貨城市 Code , （发货）
            params.deliveryContactPerson = deliveryAddress.name;
            params.deliveryContactNumber = deliveryAddress.phone;
            params.deliveryFullParentIds = deliveryAddress.fullParentIds;
            params.deliveryDetailAddress = deliveryAddress.address;
            params.deliveryCityCode = this.getCityCode(deliveryAddress.fullParentIds);

            // console.log('params', params)
            // return;//测试
            //2、提货时间（发货）
            if (pickupDateTime) {
                params.pickupDateTime = moment(pickupDateTime).format(formateTime);
            }
            //3、附件
            let unit = {
                handleFiles: (files, flag) => {
                    let arr = [];
                    if (files && files.length > 0) {
                        files.map(v => {
                            let obj = {};
                            obj.fileId = v;
                            obj.flag = flag;
                            arr.push(obj);
                        });
                    }
                    return arr;
                },

            };
            const addFiles = unit.handleFiles(filterAddFile(files), 1);
            const delFiles = unit.handleFiles(filterDeteteFile(files, this.fileList), 0);
            params.files = [...addFiles, ...delFiles];

            if (id) params.id = id; //系统单号

            //2、校验货物资料
            const infoForm = this.child.props.form;
            let relationVOS = [];

            infoForm.validateFieldsAndScroll(err => {
                let checkNo = false;
                if (params.orderNumber.length < 7) {
                    prompt({
                        content: '订单编号至少输入7位字符',
                        type: 'error'
                    })
                    checkNo = true
                }
                if (err || errors || checkNo) return;



                if (id) {
                    relationVOS = cargoInfoList[id].list.map(item => {
                        const { ...restd } = item;
                        if (item.id.includes('isNew')) {
                            const { id, ...rest } = restd;
                            return rest;
                        }
                        return restd;
                    });
                } else {
                    relationVOS =
                        Object.keys(cargoInfoList).length > 0
                            ? cargoInfoList[''].list.map(item => {
                                const { ...rest } = item;
                                return rest;
                            })
                            : [];
                }
                params.orderPartList = relationVOS;
                // console.log('=====relationVOS', relationVOS);
                // return; //测试
                this.saveOrSaveInfo(params);
            });
        });
    };

    /**
     * 保存数据
     */
    saveOrSaveInfo = params => {
        const { dispatch, formValues } = this.props;
        dispatch({
            type: allDispatchType.operate,
            payload: params,
            callback: data => {
                if (!data) return;
                this.setState(preState => ({
                    disabled: !preState.disabled,
                }));
                // return; //测试
                if (params.id) {
                    this.selectExportOSDetail(params.id);
                } else {
                    this.setTabName({
                        id: data,
                        isReplaceTab: true,
                    });
                }
                selectExportOSList({ payload: formValues, props: this.props });
            },
        });
    };

    setTabName = payload => {
        const { dispatch } = this.props;
        dispatch({
            type: allDispatchType.setTabsName,
            payload,
            callback: data => {
                if (!data) return;
                router.push(`${routeUrl.edit}/${payload.id}`);
            },
        });
    };

    handleStateChange = (options = []) => {
        options.map(item => {
            this.setState(item);
        });
    };

    onRef = ref => {
        this.child = ref;
    };
    //添加货物
    addCargoInfo = e => {
        e.stopPropagation();
        this.child.addInfo();
    };
    //移除货物
    removeInfo = e => {
        e.stopPropagation();
        const { detailId, selectedRows } = this.state;
        const { cargoInfoList } = this.props;
        const deleteIds = selectedRows.map(v => v.id);
        this.deleteInfoIds = selectedRows.filter(item => !item.id.includes('isNew')).map(v => v.id);
        const newData = cargoInfoList[detailId].list.filter(item => !deleteIds.includes(item.id));
        this.saveAllValue({ cargoInfoList: { [detailId]: { list: newData } } });
        this.handleStateChange([{ selectedRows: [], showTips: true }]);
    };
    saveAllValue = payload => {
        const { dispatch } = this.props;
        dispatch({
            type: allDispatchType.value,
            payload: payload || {},
        });
    };
    //表格显示提示：
    showTipsFun = val => {
        this.setState({
            showTips: val,
        });
    };

    changeChecked = (e, type) => {
        this.setState({
            [type]: e.target.checked,
        });
    };
    //自动获取订单编号：若点击自动获取订单编号后，按钮就禁用，但仍支持手动输入；
    getOrderNo = (e) => {
        const { dispatch, form } = this.props;
        if (!this.state.getDataFirst.orderNo) return;
        dispatch({
            type: allDispatchType.getOrderNo,
            payload: {},
            callback: (data) => {
                form.setFieldsValue({ orderNumber: data })
                this.setState({
                    getDataFirst: {
                        ...this.state.getDataFirst,
                        orderNo: false
                    }
                })
            }
        });
    }
    getCity = (detailAddress, type) => {
        const { dispatch, form } = this.props;
        const address = form.getFieldValue(detailAddress);
        if (!address) {
            prompt({
                title: '提示',
                content: '请填写详细地址',
                type: 'error'
            })
            return;
        }
        dispatch({
            type: allDispatchType.getAddress,
            payload: { address: address || "" },
            callback: (data) => {
                if (!data) return;
                this.formatAddress(data.fullParentIds, type);
            }
        });
    }

    formatAddress = (data, type) => {
        const { form } = this.props;
        let newData = data ? data.split(',') : [];
        if (newData.length > 0 && newData[0] == "0") {
            newData.shift();
        }
        if (newData.length > 4) {
            newData = newData.slice(0, 4);
        } else if (newData.length > 2 && newData.length < 4) {
            //增加数组元素，为了统一使用组件回显
            newData.length = 4;
        }
        newData = newData.join(',');
        form.setFieldsValue({ [type]: newData })
    }

    //设置地址弹窗 visibleAddress
    setAddressModal = () => {
        this.setState(pre => ({
            visibleAddress: !pre.visibleAddress
        }))
    }
    //新增或修改地址弹窗
    addAddress = (type,disabled) => {
        if(disabled) return;
        this.setAddressModal()
        this.setState(pre => ({
            addressType: type,
            addressInfo: this.state[type + 'Address'],
        }))
    }
    //获取子组件的地址信息：
    getAddressInfo = (type, info) => {
        this.setState(pre => ({
            visibleAddress: !pre.visibleAddress,
            [type]: info,
        }))
    }

    render() {
        const {
            loading,
            form: { getFieldDecorator },
            exportOSDetail,
            dictObject,
            customerList,
            match: {
                params: { id },
            },
            form,
            isMobile,

        } = this.props;
        const {
            isCustomDeclaration,
            isExportBillsPurchase,
            detailId,
            disabled,
            selectedRows,
            showTips,
            getDataFirst: {
                orderNo
            },
            visibleAddress,
            addressType,
            spickupAddress,
            deliveryAddress,
            addressInfo,
            truckTypeList,
        } = this.state;
        const detail = exportOSDetail[id] || {};
        const new_conCode = this.state.consignorCode ?this.state.consignorCode: detail.consignorCode
        ? detail.consignorCode || undefined
        : customerList.list && customerList.list.length == 1
            ? customerList.list[0].consignorCode:undefined
        let isRequire = {}
        if(new_conCode == '80102409'){
            isRequire = {
                rules: [{ required: true }]
            }
        }
       
           
        const commonParams = {
            getFieldDecorator,
        };
        const preTitle = (
            <span>
                货物资料
        {showTips && (
                    <span style={{ color: 'red', marginLeft: 30 }}>当前数据有变化，请注意保存</span>
                )}
            </span>
        );

        const editPageParams = {
            title: detail.orderNumber || '新增订单',
            headerOperate: this.headerOperate(),
            panelValue: [
                { key: '基础信息' },
                {
                    key: preTitle,
                    extra: (
                        <>
                            <AdButton
                                onClick={e => {
                                    this.removeInfo(e);
                                }}
                                ghost
                                disabled={disabled || selectedRows.length === 0}
                                text="删除"
                                type="danger"
                            />
                            <AdButton
                                type="primary"
                                disabled={disabled}
                                onClick={e => {
                                    this.addCargoInfo(e);
                                }}
                                style={{ marginLeft: 8 }}
                                text="新增"
                            />
                        </>
                    ),
                },
            ],
        };

        const formItem = [
            [
                <AntdFormItem
                    label="订单编号"
                    code="orderNumber"
                    initialValue={detail.orderNumber}
                    rules={[{ required: true }]}
                    {...commonParams}
                >
                    <AntdInput disabled={disabled} addonAfter={
                        <Tooltip title={orderNo ? "点击生成--订单编号" : ''}>
                            <Icon style={{ cursor: orderNo ? 'pointer' : 'not-allowed' }} type="reload" onClick={() => this.getOrderNo()} />
                        </Tooltip>
                    } />
                </AntdFormItem>,
                <AntdFormItem
                    label="委托方"
                    code="consignorCode"
                    initialValue={new_conCode}
                    rules={[{ required: true }]}
                    {...commonParams}
                >
                    <AdSelect
                        isExist={true}
                        show={{ id: 'consignorCode', name: 'consignorName' }}
                        disabled={disabled}
                        data={customerList.list || []}
                        onChange={(val)=>{
                            this.setState(pre=>({
                                consignorCode:val
                            }))
                        }}
                    />
                </AntdFormItem>,
            ],
            [
                <AntdFormItem
                    label="吨车/货柜尺寸"
                    code="truckType"
                    initialValue={detail.truckType}
                    rules={[{ required: true }]}
                    {...commonParams}
                >
                    <AdSelect disabled={disabled} isExist={true} data={truckTypeList} />
                </AntdFormItem>,
                <AntdFormItem
                    label="提货时间"
                    code="pickupDateTime"
                    rules={[{ required: true }]}
                    initialValue={
                        detail && detail.pickupDateTime ? moment(detail.pickupDateTime, formateTime) : null
                    }
                    {...commonParams}
                >
                    <AntdDatePicker showTime disabled={disabled} placeholder="请选择时间" />
                </AntdFormItem>,
            ],
            [
                <AntdFormItem
                    label="发货人"
                    code="address2"
                    initialValue={1}
                    rules={[{ required: true }]}
                    {...commonParams}
                >
                    {spickupAddress.name ?
                        <div className={`${styles.cusAdress} ${disabled ? styles.cusAdressDisable:''}`} onClick={() => this.addAddress('spickup',disabled)}>
                            <div> <label className={styles.name}>{spickupAddress.name}</label> <label>{spickupAddress.phone}</label></div>
                            <div>
                                <label style={{ marginRight: 3 }}>{spickupAddress.fullParentNames}</label>
                                <label title={spickupAddress.address}>{spickupAddress.address}</label>
                            </div>
                        </div>
                        :
                        <div
                        className={`${styles.addAdress} ${disabled ? styles.cusAdressDisable:''}`}
                         onClick={() => this.addAddress('spickup',disabled)}>填写发货人信息</div>
                    }
                </AntdFormItem>,
                <AntdFormItem
                    label="收货人"
                    code="address1"
                    initialValue={1}
                    rules={[{ required: true }]}
                    {...commonParams}
                >
                    {deliveryAddress.name ?
                        <div className={`${styles.cusAdress} ${disabled ? styles.cusAdressDisable:''}`} onClick={() => this.addAddress('delivery',disabled)}>
                            <div> <label className={styles.name}>{deliveryAddress.name}</label> <span>{deliveryAddress.phone}</span></div>
                            <div>
                                <label style={{ marginRight: 3 }}>{deliveryAddress.fullParentNames}</label>
                                <label title={deliveryAddress.address}>{deliveryAddress.address}</label>
                            </div>
                        </div>
                        :
                        <div 
                        className={`${styles.addAdress} ${disabled ? styles.cusAdressDisable:''}`}
                        onClick={() => this.addAddress('delivery',disabled)}>填写收货人信息</div>
                    }

                </AntdFormItem>,

            ],
            [
                <AntdFormItem
                    label="贸易条款"
                    code="incoterm"
                    initialValue={detail.incoterm}
                    {...commonParams}
                >
                    <AdSelect disabled={disabled} isExist={true} data={incotermList} />
                </AntdFormItem>,
                <AntdFormItem
                    label="结算编号"
                    code="chargeCode"
                    initialValue={detail.chargeCode}
                    // rules={[{ required: new_conCode == '80102409'?true:false }]}
                    {...commonParams}
                    {...isRequire}
                >
                    <AntdInput disabled={disabled} />
                </AntdFormItem>,
            ],
            [
                <div className="cus_removeColon">
                    <AntdFormItem
                        label=" "
                        code="isCustomDeclaration"
                        initialValue={isCustomDeclaration || false}
                        {...commonParams}
                    >
                        <Checkbox
                        disabled={disabled}
                            checked={isCustomDeclaration || false}
                            onChange={val => this.changeChecked(val, 'isCustomDeclaration')}
                        >
                            需要报关服务
            </Checkbox>
                    </AntdFormItem>
                </div>,
                <div className="cus_removeColon">
                    <AntdFormItem
                        label=" "
                        code="isExportBillsPurchase"
                        // rules={[{ required: true }]}
                        initialValue={isExportBillsPurchase || false}
                        {...commonParams}
                    >
                        <Checkbox
                        disabled={disabled}
                            checked={isExportBillsPurchase || false}
                            onChange={val => this.changeChecked(val, 'isExportBillsPurchase')}
                        >
                            需要出口买单
                        </Checkbox>
                    </AntdFormItem>
                </div>,
            ],
            [
                <AntdFormItem label="备注" code="remark" initialValue={detail.remark} {...commonParams}>
                    <TextArea rows={4} disabled={disabled} />
                </AntdFormItem>,
            ],
            [
                <AntdFormItem label="附件" code="files" initialValue={detail.files || []} {...commonParams}>
                    <FileReader urlType="tms" disabled={disabled} />
                </AntdFormItem>,
            ],
        ];

        return (
            <div className="cus_exportOSOperate">
                <EditPage {...editPageParams}>
                    <Spin spinning={detailId ? loading : false}>
                        <AntdForm>{formItemFragement(formItem)}</AntdForm>
                    </Spin>
                    <Fragment>
                        <ExportOSInfo
                            detailId={detailId}
                            onlyRead={false}
                            onRef={this.onRef}
                            selectedRows={selectedRows}
                            disabled={disabled}
                            onSelectRow={selectedRows => this.handleStateChange([{ selectedRows }])}
                            showTipsFun={this.showTipsFun}
                        />
                    </Fragment>
                </EditPage>
                {visibleAddress && (
                    <ExportAddress
                        visibleAddress={visibleAddress}
                        getAddressInfo={this.getAddressInfo}
                        addressType={addressType}
                        setAddressModal={this.setAddressModal}
                        p_addressInfo={addressInfo}
                        userToken={this.userToken} />
                )}
            </div>
        );
    }
}
